//
//  KSCLyricsParser.swift
//  KSC歌词解析器
//
//  Created by smile on 2019/4/20.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

class KSCLyricsParser {
    static func parse(_ style:LyricType,_ data:String) -> Lyric {
        let result=Lyric()
        result.isAccurate=true
        
        result.datas=[]
        
        //使用\n拆分歌词
        let strings=data.components(separatedBy: "\n")
        
        for line in strings {
            //解析每一行
            if let lyricLine=parseLine(line){
                result.datas.append(lyricLine)
            }
        }
        
        return result;
    }
    
    /// 解析每一行歌词
    /// 例如：karaoke.add('00:27.487', '00:32.068', '一时失志不免怨叹', '347,373,1077,320,344,386,638,1096');
    ///
    /// - Parameter data: <#data description#>
    /// - Returns: <#return value description#>
    static func parseLine(_ data:String) -> LyricLine? {

        if data.hasPrefix("karaoke.add(") {
            //只解析歌词
            //其他的元数据
            //没用到所有不解析
            
            let lyricLine=LyricLine()
            
            //歌词开始，过滤了前面的元数据
            //移除开始位置"karaoke.add('"字符串
            //移除后面的');
            let newData = data[13..<data.count-3]
            
            //', '拆分
            let comands=newData.components(separatedBy: "', '")
            
            //开始时间
            lyricLine.startTime=TimeUtil.parseToInt(comands[0])
            
            //结束时间
            lyricLine.endTime=TimeUtil.parseToInt(comands[1])
            
            //歌词
            let lyricString=comands[2]
            
            //整行歌词
            lyricLine.data=lyricString

            //将歌词拆分为单个字
            //这里没有解析英文歌曲的KSC
            lyricLine.words=lyricString.words()

            //每个字时间
            lyricLine.wordDurations=[]

            let lyricTimeString=comands[3]
            
            let lyricTimeWords=lyricTimeString.components(separatedBy: ",")
   
            //将每个元素转为int,为了后面方便计算
            for item in lyricTimeWords {
                lyricLine.wordDurations!.append(Int(item)!)
            }
 
            return lyricLine
        }
        
        return nil
    }
    
}
